

#include "servo_device.h"

// d_distr:2,1,1,0,1,2000000000,
static e_device_err cc_servo_read_cb(void* user_data, const char* msg, int type,
                                     void* data)
{
  user_device_t dev = (user_device_t)user_data;
  if (dev == CC_NULL)
  {
    cc_log_e("device is null\r\n");
    return DEVICE_ENULL;
  }
  Servo* servo = (Servo*)dev->hard_drv;
  if (servo == CC_NULL)
  {
    cc_log_e("hard drive is null\r\n");
    return DEVICE_EHARD_DRV_NULL;
  }

  cc_log("cc_servo_read_cb\r\n");
  return DEVICE_EOK;
}
static e_device_err cc_servo_write_cb(void* user_data, const char* msg, int type,
                                      void* data)
{
  user_device_t dev = (user_device_t)user_data;
  if (dev == CC_NULL)
  {
    cc_log_e("device is null\r\n");
    return DEVICE_ENULL;
  }
  Servo* servo = (Servo*)dev->hard_drv;
  if (servo == CC_NULL)
  {
    cc_log_e("hard drive is null\r\n");
    return DEVICE_EHARD_DRV_NULL;
  }

  cc_log("cc_servo_write_cb\r\n");
  return DEVICE_EOK;
}
static e_device_err cc_servo_control_cb(void* user_data, const char* msg, int type,
                                        void* data)
{
  user_device_t dev = (user_device_t)user_data;
  if (dev == CC_NULL)
  {
    cc_log_e("device is null\r\n");
    return DEVICE_ENULL;
  }
  Servo* servo = (Servo*)dev->hard_drv;
  if (servo == CC_NULL)
  {
    cc_log_e("hard drive is null\r\n");
    return DEVICE_EHARD_DRV_NULL;
  }
  cc_log_d("cc_servo_control_cb\r\n");
  if (msg != CC_NULL)
  {
    cc_log("recv:%s\r\n", msg);
    // 适用于180°舵机
    if (CC_SERVO_ANGLE == type)
    {
      int angle = atoi(msg);
      if (angle >= 0 && angle <= 180)
        servo->write(angle);
    }
  }
  // 适用于360°舵机
  if (CC_SERVO_OPEN == type)
  {
    servo->write(0);
  }
  if (CC_SERVO_STOP == type)
  {
    servo->write(90);
  }
  if (CC_SERVO_CLOSE == type)
  {
    servo->write(180);
  }

  return DEVICE_EOK;
}

static e_device_err cc_servo_control_exit_cb(void* user_data)
{
  cc_log("cc_servo_control_exit_cb\r\n");
  return DEVICE_EOK;
}

static e_device_err cc_servo_read_exit_cb(void* user_data)
{
  cc_log("cc_servo_read_exit_cb\r\n");
  return DEVICE_EOK;
}

static e_device_err cc_servo_write_exit_cb(void* user_data)
{
  cc_log("cc_servo_write_exit_cb\r\n");
  return DEVICE_EOK;
}

e_device_err cc_servo_init(void* device)
{
  user_device_t dev = (user_device_t)device;

  dev->hard_drv = new Servo();
  Servo* servo = (Servo*)dev->hard_drv;
  servo->attach(dev->pin[0]);
  dev->control_cb = cc_servo_control_cb;
  dev->read_cb = cc_servo_read_cb;
  dev->write_cb = cc_servo_write_cb;
  return DEVICE_EOK;
}
CC_DEVICE_INIT_MOUNT(cc_servo_init, CC_DEVICE_TYPE_SERVO)
